package com.chhuang.tutool.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.chhuang.tutool.R
import com.chhuang.tutool.databinding.AdapterSocketItemLayoutBinding
import com.chhuang.tutool.modle.SocketBean

/**
 * item适配器
 */
class SocketListAdapter(private var socketList: MutableList<SocketBean>,
                        private val onItemClick:(view: View, position: Int, o: Any)->Unit) : Adapter<SocketListAdapter.ViewHolder>() {
    companion object{
        private const val TAG = "SocketListAdapter"
        private val imageBackgroundDrawable = listOf(
            R.drawable.item_background_blue_jeans,
            R.drawable.item_background_grapefruit,
            R.drawable.item_background_lavender,
            R.drawable.item_background_mint,
            R.drawable.item_background_sunflower)
    }

    private lateinit var socketTypeParams: Array<String>

    inner class ViewHolder(val binding: AdapterSocketItemLayoutBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        socketTypeParams = parent.context.resources.getStringArray(R.array.socket_type)
        val binding = AdapterSocketItemLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        with(holder){
            with(socketList[position]){
                binding.root.setBackgroundResource(imageBackgroundDrawable[this.socketType])
                binding.socketTextView.text = """${socketTypeParams[this.socketType]}  ${if(this.socketType==2) this.loaclPort else ""}"""
                binding.socketDetailTextView.text = "${this.ip}:${this.port}"
                itemView.setOnClickListener {
                    onItemClick(it, position,this)
                }
            }
        }
    }

    override fun getItemCount(): Int {
        return socketList.size
    }

    fun refresh(sockets: List<SocketBean>) {
        val len = socketList.size
        socketList = mutableListOf()
        this.notifyItemRangeRemoved(0, len)
        if(sockets.isNotEmpty()){
            socketList = sockets.toMutableList()//这里不能直接用=，不然就是引用传递删除的时候len获取不到之前的，用toMutableList就是copy一份
            this.notifyItemRangeInserted(0, socketList.size)
        }
    }

    fun loadMore(sockets: List<SocketBean>) {
        val len = socketList.size
        socketList.addAll(sockets)
        this.notifyItemRangeInserted(len, sockets.size)
    }
}